// 云函数入口文件
const cloud = require('wx-server-sdk')

//1.
var yly = require('yly-nodejs-sdk'); 

var repeat = require('repeat-string');




cloud.init()

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()


  //2.
  var accessToken = "6f0e017cb00d44088acc055c79209489";
  var config = new yly.Config({
    'cid': '1074764767',         //应用id
    'secret': '7f3d32a5f67e1da27280eb6b9f2773d6'       //应用秘钥
  });

  console.log("11111111111=====" + config);
  console.log(config);
  //3.
  var oauthClient = new yly.OauthClinet(config);
  console.log("222222222222=====");
  console.log(oauthClient);

  var tokenData = null;
  var rea77 = null;
  console.log("33333333333=====");


  //4.
  // await oauthClient.getToken().then(function (res) {

  //   console.log("44444444444=====");
  //   console.log(res);
  //   if (
  //     res.error != 0 &&
  //     res.error_description != 'success'
  //   ) {
  //     throw new Error('failed:' + res.error_description);
  //   }
  //   tokenData = {
  //     'accessToken': res.body.access_token,
  //     'refreshToken': res.body.refresh_token,
  //   };
  //   if (res.body.machine_code != null) {
  //     tokenData.machineCode = res.body.machine_code;
  //   }
  //   console.log(tokenData);
  // });
  //
  //5
  var RpcClient = new yly.RpcClient(accessToken, config);

  //6
  var Print = new yly.Print(RpcClient);

  //7
  var machineCode = "4004601938";//易联云打印机终端号
  var originId = "3F2504E0-4F89-11D3-9A0C-0305E82C3301";//打印订单的编号
  var content = "<FS2><center>**时代速派电工**</center></FS2>";
  content += repeat('*', 32);
  content += "<FS><center>--订单信息--</center></FS>";
  content += "订单号: 201903029870C3\n";
  content += "下单时间: 2019-03-29 16:23:37\n";
  content += repeat('*', 32);
  content += "<FS><center>--故障信息--</center></FS>";
  content += "故障名称: 我的设备开不了机\n";
  content += "故障类型: 机器设备维修\n";
  content += "故障级别: b级故障(预估500元)\n";
  content += "故障描述: 我的设备开不了机了,已经有一个信息了,希望快点派人来维修.谢谢\n";
  content += repeat('*', 32);
  content += "<FS><center>--联系人信息--</center></FS>";
  content += "姓名: 李貌\n";
  content += "电话: 18908561989\n";
  content += "地址: 深圳市南山区科技中二路十号594\n";
  content += repeat('*', 32);
  content += "<FS><center>-微信扫一扫进入小程序-</center></FS>";
  content += repeat('.', 32);
  content += "<QR>https://mp.weixin.qq.com/a/~zTx_7V2b7eeS17YBX9UDCw~~</QR>";
  content += repeat('*', 32);
  content += "<FS2><center>**#1 完**</center></FS2>";

  await Print.index(machineCode, originId, content).then(function (res) {
    console.log("77777777777777777777");
    rea77 = res;
    console.log(res);
  });

  return {
    event,
    rea77,
    openid: wxContext.OPENID,
    appid: wxContext.APPID,
    unionid: wxContext.UNIONID,
  }
}